﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.IO;
using System.Reflection;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls.WebParts;
using System.Collections;

namespace SCCL2010
{
    public static class Pages
    {
        private const string cFileLoc = "SCCL2010.Files.";

        /// <summary>
        /// Gets the ResourceStream for the supplied ResourceName.
        /// </summary>
        /// <param name="resourceName"></param>
        /// <returns>returns a stream object representing the specified Manifest for the current assembly.</returns>
        public static Stream GetWebPartPage(wpPageTypes oType)
        {
            try
            {
                string cFileName = "";
                if (oType == wpPageTypes.FullPageVertical) cFileName = cFileLoc + "FullPageVertical.aspx";
                if (oType == wpPageTypes.HeaderFooter2Columns4Rows) cFileName = cFileLoc + "HeaderFooter2Columns4Rows.aspx";
                if (oType == wpPageTypes.HeaderFooter3Columns) cFileName = cFileLoc + "HeaderFooter3Columns.aspx";
                if (oType == wpPageTypes.HeaderFooter4ColumnsTopRow) cFileName = cFileLoc + "HeaderFooter4ColumnsTopRow.aspx";
                if (oType == wpPageTypes.HeaderLeftColumnBody) cFileName = cFileLoc + "HeaderLeftColumnBody.aspx";
                if (oType == wpPageTypes.HeaderRightColumnBody) cFileName = cFileLoc + "HeaderRightColumnBody.aspx";
                if (oType == wpPageTypes.LeftColumnHeaderFooterTopRow3Columns) cFileName = cFileLoc + "LeftColumnHeaderFooterTopRow3Columns.aspx";
                if (oType == wpPageTypes.RightColumnHeaderFooterTopRow3Columns) cFileName = cFileLoc + "RightColumnHeaderFooterTopRow3Columns.aspx;";

                Stream oStream = GetResourceStream(cFileName);
                return oStream;
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError("GetWebPartPage", ex);
            }
            return null;
        }

        /// <summary>
        /// Gets the ResourceStream for the supplied ResourceName.
        /// </summary>
        /// <param name="resourceName"></param>
        /// <returns>returns a stream object representing the specified Manifest for the current assembly.</returns>
        public static Stream GetResourceStream(string resourceName)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            return assembly.GetManifestResourceStream(resourceName);
        }

        /// <summary>
        /// Method to add a page to the webpart library
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="cLibraryName"></param>
        /// <param name="cWebPageName"></param>
        /// <param name="strViewPage"></param>
        public static void AddPageToWebPartLibary(SPWeb oWeb, string cLibraryName, string cWebPageName, Stream strViewPage)
        {
            try
            {
                SPList lstLibrary = oWeb.Lists[cLibraryName];
                if (!Libraries.HasFile(lstLibrary.RootFolder, cWebPageName))
                {

                    SPFile oSPFile = lstLibrary.RootFolder.Files.Add(cWebPageName, strViewPage);
                }
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(oWeb, "AddPageToWebPartLibary", ex);
            }
        }

        public static void EnsureWebPartPage(SPWeb oWeb, string cLibraryName, string cWebPageName,wpPageTypes PageType)
        {
            try
            {
                Stream strViewPage = GetWebPartPage(PageType);
                SPList lstLibrary = oWeb.Lists[cLibraryName];
                if (!Libraries.HasFile(lstLibrary.RootFolder, cWebPageName))
                {
                    SPFile oSPFile = lstLibrary.RootFolder.Files.Add(cWebPageName, strViewPage);
                }
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(oWeb, "AddPageToWebPartLibary", ex);
            }
        }

        public static bool HasListViewOnPage(SPWeb oWeb, string cLibraryName, string cWebPageName, string cListName, string cViewName)
        {
            SPList lstLibrary = oWeb.Lists[cLibraryName];
            SPFile page = null;
            if (lstLibrary.EnableVersioning)
            {
                page = oWeb.GetFile(String.Format("{0}/{1}", cLibraryName, cWebPageName));
                if (page.CheckOutType != SPFile.SPCheckOutType.None)
                    page.CheckIn("");
                page.CheckOut();
            }
            SPListItem selecteditem = GetPageItem(lstLibrary, cWebPageName);
            if (selecteditem != null)
            {
                SPLimitedWebPartManager mgr = oWeb.GetLimitedWebPartManager(selecteditem.Url, PersonalizationScope.Shared);
                foreach (Microsoft.SharePoint.WebPartPages.WebPart item in mgr.WebParts)
                {
                    System.Diagnostics.Trace.WriteLine(item.GetType().ToString());
                }
            }
            return false;
        }


        public static void EnsureListViewOnPage(SPWeb oWeb, string cLibraryName, string cWebPageName, string cZone, int iZoneIndex,  string cListName, string cViewName, string cTitle)
        {
            if (!HasListViewOnPage(oWeb, cLibraryName, cWebPageName, cListName, cViewName))
            {
                AddListViewToPage(oWeb, cLibraryName, cWebPageName, cZone, iZoneIndex, false, cListName, cViewName, cTitle);
            }
            
        }



        public static void AddListViewToPage(SPWeb oWeb, string cLibraryName, string cWebPageName, string cZone, int iZoneIndex, bool bClearParts, string cListName, string cViewName,string cTitle)
        {
            if (Lists.HasList(oWeb, cListName))
            {
                SPList oList = oWeb.Lists[cListName];
                SPView oView=null;
                if (Lists.HasView(oList, cViewName))
                {
                    oView = oList.Views[cViewName];
                }
                else
                {
                    oView = Lists.GetDefaultView(oList);
                }
                     using (ListViewWebPart oListView = new ListViewWebPart { Title = cTitle, 
                                                                       ListName = oList.ID.ToString() , 
                                                                       ViewGuid = oView.ID.ToString(), 
                                                                       WebId = oWeb.ID, 
                                                                       ChromeType = PartChromeType.TitleOnly, 
                                                                       TitleUrl = oWeb.Url })
                     {
                         AddWebPartToPage(oWeb,cLibraryName ,cWebPageName ,cZone ,iZoneIndex,bClearParts , oListView);
                     }
            }
        }




        /// <summary>
        /// Retrieves the SPListItem based on the Page.
        /// </summary>
        /// <param name="oList"></param>
        /// <param name="cPageName"></param>
        /// <returns>returns a SPListItem for the specified PageName.</returns>
        private static SPListItem GetPageItem(SPList oList, string cPageName)
        {
            foreach (SPListItem item in oList.Items)
            {
                if (item.Name == cPageName)
                {
                    return item;
                }
            }
            return null;
        }

        /// <summary>
        /// Method to add Webpart to the specified Page.
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="cLibraryName"></param>
        /// <param name="PageName"></param>
        /// <param name="cZone"></param>
        /// <param name="iZoneIndex"></param>
        /// <param name="bClearParts"></param>
        /// <param name="oWebPart"></param>
        public static void AddWebPartToPage(SPWeb oWeb, string cLibraryName, string PageName, string cZone, int iZoneIndex, bool bClearParts, Microsoft.SharePoint.WebPartPages.WebPart oWebPart)
        {
            SPList lstLibrary = oWeb.Lists[cLibraryName];
            SPFile page = null;
            if (lstLibrary.EnableVersioning)
            {
                page = oWeb.GetFile(String.Format("{0}/{1}", cLibraryName, PageName));
                if (page.CheckOutType != SPFile.SPCheckOutType.None)
                    page.CheckIn("");
                page.CheckOut();
            }
            SPListItem selecteditem = GetPageItem(lstLibrary, PageName);
            if (selecteditem != null)
            {
                SPLimitedWebPartManager mgr = oWeb.GetLimitedWebPartManager(selecteditem.Url, PersonalizationScope.Shared);
                if (bClearParts)
                {
                    ArrayList DeleteParts = new ArrayList();
                    foreach (Microsoft.SharePoint.WebPartPages.WebPart item in mgr.WebParts)
                    {
                        DeleteParts.Add(item);
                    }
                    for (int i = 0; i < DeleteParts.Count; i++)
                    {
                        mgr.DeleteWebPart((Microsoft.SharePoint.WebPartPages.WebPart)DeleteParts[i]);
                    }
                }
                oWebPart.ChromeType = PartChromeType.None;
                mgr.AddWebPart((Microsoft.SharePoint.WebPartPages.WebPart)oWebPart, cZone, iZoneIndex);

            }
            if (lstLibrary.EnableVersioning)
            {
                if (page.CheckOutType != SPFile.SPCheckOutType.None)
                    page.CheckIn("");
                page.Publish("Web Part Added");
            }
        }

        /// <summary>
        /// Method to add Webpart to the specified Page.
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="PageName"></param>
        /// <param name="cZone"></param>
        /// <param name="iZoneIndex"></param>
        /// <param name="bClearParts"></param>
        /// <param name="oWebPart"></param>
        public static void AddWebPartToPage(SPWeb oWeb, string PageName, string cZone, int iZoneIndex, bool bClearParts, Microsoft.SharePoint.WebPartPages.WebPart oWebPart)
        {
            SPFile page = oWeb.GetFile(PageName);
            if (page.CheckOutType != SPFile.SPCheckOutType.None)
                page.CheckIn("");
            page.CheckOut();

            SPLimitedWebPartManager mgr = oWeb.GetLimitedWebPartManager(PageName, PersonalizationScope.Shared);
            if (bClearParts)
            {
                ArrayList DeleteParts = new ArrayList();
                foreach (Microsoft.SharePoint.WebPartPages.WebPart item in mgr.WebParts)
                {
                    DeleteParts.Add(item);
                }
                for (int i = 0; i < DeleteParts.Count; i++)
                {
                    mgr.DeleteWebPart((Microsoft.SharePoint.WebPartPages.WebPart)DeleteParts[i]);
                }
            }
            oWebPart.ChromeType = PartChromeType.None;
            mgr.AddWebPart((Microsoft.SharePoint.WebPartPages.WebPart)oWebPart, cZone, iZoneIndex);

        }

        /// <summary>
        /// Used to create webpart page library.
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="cLibInternalName"></param>
        /// <param name="cLibName"></param>
        public static void CreateWebPartPageLibrary(SPWeb oWeb, String cLibInternalName, String cLibName)
        {
            try
            {
                Libraries.CreateLibrary(oWeb, cLibInternalName);
                if (Lists.HasList(oWeb, cLibInternalName))
                {
                    ArrayList contentTypes = new ArrayList();
                    SPDocumentLibrary oDocs = (SPDocumentLibrary)oWeb.Lists[cLibInternalName];
                    oDocs.ContentTypesEnabled = true;
                    oDocs.Update();


                    if (!ContentTypes.HasContentType(oDocs, "Web Part Page"))
                    {
                        SPContentType oCT = oWeb.ContentTypes["Web Part Page"];
                        oDocs.ContentTypes.Add(oCT);

                    }
                    oDocs.Hidden = false;
                    oDocs.Update();
                    if (cLibInternalName != cLibName)
                    {
                        oDocs.Title = cLibName;
                    }
                    foreach (SPContentType ct in oDocs.ContentTypes)
                    {
                        if (ct.Name != "Web Part Page" && ct.Name != "Folder")
                        {
                            contentTypes.Add(ct);
                        }
                    }
                    foreach (SPContentType ct in contentTypes)
                    {
                        oDocs.ContentTypes[ct.Id].Delete();
                    }
                    oDocs.Update();
                }
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(oWeb, "Error Adding WebPart Page Library", ex);
            }

        }







    }

    public enum wpPageTypes
    {
        FullPageVertical = 1,
        HeaderFooter2Columns4Rows = 2,
        HeaderFooter3Columns = 3,
        HeaderFooter4ColumnsTopRow = 4,
        HeaderLeftColumnBody = 5,
        HeaderRightColumnBody = 6,
        LeftColumnHeaderFooterTopRow3Columns = 7,
        RightColumnHeaderFooterTopRow3Columns = 8
    }
}
